package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io"
	"net/http"
	"os"
	"strings"
	"wxcloudrun-golang/config"
)

type OssController struct {
	BaseController
}

func (con OssController) OSSStorage(c *gin.Context) {
	coverFile, err := c.FormFile("cover")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No cover file uploaded"})
		return
	}
	// 打开文件
	srcFile, err := coverFile.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to open uploaded file"})
		return
	}
	defer srcFile.Close()

	lastDotIndex := strings.LastIndex(coverFile.Filename, ".")

	// 如果存在'.'，则截取其后的字符串作为扩展名
	var extension string
	if lastDotIndex != -1 {
		extension = coverFile.Filename[lastDotIndex:]
	} else {
		// 如果没有'.'，则没有扩展名
		extension = ""
	}
	// 生成新的文件名
	newFileName := /*config.BucketName*/ uuid.New().String() + extension
	// 将文件保存到服务器的临时目录
	tempFile, err := os.Create("temp/" + newFileName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create temp file"})
		return
	}
	defer tempFile.Close()
	// 将请求中的文件流复制到临时文件
	_, err = tempFile.Seek(0, 0)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to seek temp file"})
		return
	}
	_, err = io.Copy(tempFile, srcFile)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to write temp file"})
		return
	}
	// 上传文件到OSS
	err = config.UploadToOSS(newFileName, "temp/"+newFileName)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to upload to OSS"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "" +
		"文件上传成功", "url": "https://" + config.BucketName + "." + config.Endpoint + "/" + newFileName})
}
